// 获取应用实例
const app = getApp()
import {
    dateFormat,
    toast,
    scanfIBeacon,
    stopScanfIBeacon,
    reportEvent
} from '../../utils/util.js'
import {
    postPunchIn, // 下班打卡
    clockInPageData, // 打卡页面数据
    ibeaconCheck // ibeacon校验
} from '../../api/app'
import {
    queryVerifyResult
} from '../../api/salary-card.js'
import {
    verifyFace,
    openSalaryCard,
    querySalaryCard
} from '../../utils/salary-card.js'
import user from '../../utils/user.js'
import { amapRegeo } from '../../api/util'
import  global from '../../utils/global'

Page({
    data: {
        detailList: {}, // 原始数据
        toWorkStatus: 1, // 上班状态 1 正常 0迟到 2不显示
        offWorkStatus: 1, // 下班状态 1 正常 0早退 2不显示
        commutingStatus: true, // 只有上班和下班都是 正常 那么他才是true
        range: '',
        circularColour: 0, // 0是不在范围 1在范围,
        clockInTime: true,
        describeRange: '正在定位，打卡位置:',
        signInName: '定位中',
        signInType: 0,
        currentTime: '',
        withdrawStatus: '', // 1已提现2请联系驻场0带提现
        optionsId: '',
        optionsType: '', // 1长期工 0短期工
        latitudeAndLongitude: '', // 下班打卡接口经纬度
        changeDate: '', // 选择上面日期发生改变
        toBeWithdrawn: '', // 是否显示提现
        leaveEarly: false, // true显示蓝色正常 false显示黄色早退,
        latitude: '', // 纬度
        longitude: '', // 经度
        todayDate: '',
        signTimeStart: '', // 上班时间戳
        signTimeEnd: '', // 下班时间戳
        startTime:'',// 上班时间
        endTime:'',// 下班时间
        signInMode: 0, // 0 拍照打卡 1 人脸打卡
        // isNormal:"0"//判断当天打卡是否正常
        initDate: '', // 日历中初始化日期
        companyId: '',
        isScanf: false,
        devices: [],
        macAddressList: [], // 项目所需要的设备列表
        formatAddress: '',
        
    },
    static: {
        authenticateNumber: '', // 用于判断是否跳转开通薪工卡
        signVoucher: '', // 拍照打卡图片URL
        isOpenClock: false, // 是否全天打卡
    },
    onLoad(options) {
        let format = dateFormat('YYYY-mm-dd', new Date())
        this.setData({
            optionsId: options.id,
            optionsType: options.type,
            todayDate: format
        })

        // 更新打卡时间
        this.updateTime()
        setInterval(() => {
            this.updateTime()
        }, 1000)
    },
    onUnload() {
        this.stopLocation()
        this.stopScanf()
    },
    onShow() {
        // 薪工卡回到页面逻辑
        if (this.static.authenticateNumber && app.options.scene == 1038) {
            queryVerifyResult({
                authenticateNumber: this.static.authenticateNumber,
                companyId: this.data.companyId
            }).then(res => {
                this.static.authenticateNumber = ''
                if (res.authenticateState === 'AUTHENTICATE_SUCCESS') {
                    this.punchIn()
                }
                else{
                    // 上报事件， 人脸失败
                    reportEvent('clock', {
                        'status': 0,
                        'failmsg': 'face',
                        'userid': user.userId,
                        'remark': '人脸失败'
                    })
                }
            })
            app.options = {}
        }
        // 打开页面时如未开通将跳转开通薪工卡
        else if(this.data.companyId){
            
        }
    },
    // 初始化所有显示内容
    async initShow(time){
        // 初始化时间
        const format = this.data.todayDate
        if (!time) time = format
        const result = await clockInPageData({
            projectId: this.options.id,
            nowDate: time
        })

        this.setData({
            detailList: result,
            macAddressList: result.macAddressList,
            companyId: result.companyId,
            signInType: result.signInType,
            signInMode: result.signInMode,
            changeDate: time
        })

        this.static.isOpenClock= (result.signTimeEnd == '00:00' && result.signTimeStart == '00:00')

        // 旧数据处理回显
        this.initClockData(result)

        // 处理打卡按钮逻辑
        this.initButton(result)

        // 处理提示逻辑
        this.initTips(result)
    },
    // 初始化考勤数据回显逻辑
    initClockData(res){
        // 员工需要打卡时间
        const timeStart = this.data.changeDate + ' ' + res.signTimeStart
        const timeEnd = this.data.changeDate + ' ' + res.signTimeEnd
        const needSignTimeStart = Date.create(timeStart).getTime()
        let needSignTimeEnd = Date.create(timeEnd).getTime()

        // 全天打卡
        const isOpenClock = this.static.isOpenClock

        // 员工实际打卡时间
        const signTimeInStamp = res.signTimeIn // 上班打卡时间 
        const signTimeOutStamp = res.signTimeOut // 下班打卡时间 
        const signTimeIn = Date.create(signTimeInStamp).getTime() // 上班打卡时间戳 
        const signTimeOut = Date.create(signTimeOutStamp).getTime() // 下班打卡时间戳

        // 批量声明标识符
        let toWorkStatus = 2 // 上班打卡显示是否正常
        let offWorkStatus = 2 // 下班打卡显示是否正常
        let commutingStatus = 2 // 当条记录显示是否正常


        // 判断是否夜班打卡
        const isNight = (needSignTimeStart > needSignTimeEnd) ? dateFormat('YYYY-mm-dd', new Date(new Date() - 24 * 60 * 60 * 1000)) : false // 是夜班的话isNight为当天的前一天

        if (isNight) {
            // 如果是夜班,给下班卡增加24小时
            needSignTimeEnd += 24 * 60 * 60 * 1000

            // 当前时间小于下班时间3小时以内，允许在前一天打卡
            this.setData({
                isNightOk: (new Date().getTime() < (needSignTimeEnd + 3 * 60 * 60 * 1000) ? isNight : false)
            })

            // 如果是夜班，当前时间没有超达到第二天的上班时间，就将页面转到前一天
            if (new Date().getTime() < (needSignTimeStart - 4 * 60 * 60 * 1000) && !this.data.initDate) {
                this.setData({
                    initDate: isNight
                })
                // 跳转到前一天后重新初始化
                return 
            }
        }

        // 上班打卡显示处理
        if (signTimeInStamp === null) {
            toWorkStatus = 2
        } else if (needSignTimeStart >= signTimeIn || isOpenClock) {
            toWorkStatus = 1
        } else {
            toWorkStatus = 0
        }

        // 下班打卡显示处理
        if (signTimeOutStamp === null) {
            offWorkStatus = 2
        } else if (needSignTimeEnd <= signTimeOut || isOpenClock) {
            offWorkStatus = 1
        } else {
            offWorkStatus = 0
        }

        // 判断上下班打卡是否正常
        if(isOpenClock){ // 全天打卡默认正常
            commutingStatus = 1
        }
        else if (toWorkStatus == 2 && offWorkStatus == 2) {
            commutingStatus = 2
        }else if(toWorkStatus == 1 && offWorkStatus == 2 && this.data.detailList.date !== this.data.todayDate){
            commutingStatus = 0
        }else if(toWorkStatus == 1 && offWorkStatus == 2){
            // 上班正常但是下班还没打卡的情况 显示正常
            commutingStatus = 1
        }else if (toWorkStatus != 1 || offWorkStatus != 1) {
            commutingStatus = 0
        }else {
            commutingStatus = 1
        }
        // 挂载到页面
        this.setData({
            toWorkStatus,
            offWorkStatus,
            commutingStatus
        })
    },
    // 初始化打卡按钮显示逻辑
    initButton(res){
        const gitPositionInformation = (longitude, latitude)=>{
            console.log('反复调用1111')
            // 获取需要打卡的坐标（获取整数防止浮点数运算）
            const companyCoordinateX = parseInt(this.data.detailList.signLocation == null || this.data.detailList.signLocation.split(',')[0] * 1000000)
            const companyCoordinateY = parseInt(this.data.detailList.signLocation == null || this.data.detailList.signLocation.split(',')[1] * 1000000)

            // 获取当前坐标
            const longitudeX = parseInt(longitude * 1000000)
            const latitudeY = parseInt(latitude * 1000000)

            // 获取打卡范围
            let signRange = this.data.detailList.signRange * 10

            // 当前时间戳
            const timeStamp = new Date().getTime()

            // 员工需要打卡时间
            const timeStart = this.data.changeDate + ' ' + res.signTimeStart
            const timeEnd = this.data.changeDate + ' ' + res.signTimeEnd
            const needSignTimeStart = Date.create(timeStart).getTime()
            let needSignTimeEnd = Date.create(timeEnd).getTime()
            needSignTimeEnd += needSignTimeStart > needSignTimeEnd ? 24 * 60 * 60 * 1000 : 0

            // 全天打卡
            const isOpenClock = this.static.isOpenClock

            // 拍照打卡
            const isPhoto = this.data.signInMode == 0
            const photoText = isPhoto ? '拍照' : ''
            
            // 确定打卡类型，上班、下班
            const isToWork = !this.data.detailList.signTimeIn

            // 迟到
            const isLate = !isOpenClock && isToWork && needSignTimeStart < timeStamp
            // 早退
            const isEarly = !isOpenClock && !isToWork && needSignTimeEnd > timeStamp
            // 是否处于打卡时间段
            const isnotClockTime = !isOpenClock && timeStamp < needSignTimeStart - 3 * 60 * 60 * 1000
            // 是否超出打卡时间段
            const isOutClockTime = !isOpenClock && timeStamp > needSignTimeEnd + 3 * 60 * 60 * 1000

            // 是否处于打卡范围
            const isInLocation =  isPhoto || (longitudeX > companyCoordinateX - signRange && longitudeX < companyCoordinateX + signRange && latitudeY > companyCoordinateY - signRange && latitudeY < companyCoordinateY + signRange)

            
            // 是否可以打卡
            const circularColour = !isnotClockTime &&  !isOutClockTime && isInLocation
            // 是否异常打卡
            const leaveEarly = isLate || isEarly
            // 显示备注
            const describeRange = !isInLocation ? '暂未进入打卡范围 ' : (isnotClockTime ? '未达到打卡时间段,已进入打卡范围 ' : (isOutClockTime ? '超出打卡时间段,已进入打卡范围 ' : '已进入打卡范围'))
            // 显示标题
            let signInName = ''

            // 标题文字处理
            if(!circularColour){
                signInName = '不可打卡'
            }
            else if(leaveEarly){
                signInName = isLate ? `${photoText}迟到打卡` : `${photoText}早退打卡`
            }
            else if(isPhoto){
                signInName = '拍照打卡'
            }
            else{
                signInName = isToWork ? `${photoText}上班打卡` : `${photoText}下班打卡`
            }

            // 拍照打卡获取当前位置文字
            if(isPhoto){
                const location = this.data.latitude + ',' + this.data.longitude
                console.log(location,'反复调用')
                amapRegeo({
                    location
                }).then(res=>{
                    this.setData({
                        formatAddress:  res.result.address
                    })
                })
            }

            // 定义显示内容
            this.setData({
                circularColour,
                leaveEarly,
                describeRange,
                signInName,
                longitude,
                latitude
            }) 
        }
        wx.getSetting({
            success (res) {
                if (!res.authSetting['scope.userLocation']) {
                    app.alert('未授权获取位置信息权限无法打卡，请授权后再试').then(()=>{
                        wx.openSetting()
                    })
                }else{
                    wx.getLocation({
                        type: 'gcj02',
                        isHighAccuracy:true,
                        success: (res) => {
                            console.log(res, 'resres')
                            console.log('329')
                            gitPositionInformation(res.longitude, res.latitude)
                        },
                        fail: (rej) => {
                            if(this.data.signInMode === 0){
                                console.log(rej, 'rejrej') 
                                this.stopLocation()
                                console.log('344')
                                gitPositionInformation(0, 0)
                            }
                        }
                    })
                }
            }
        })
    },
    // 初始化所有提示
    async initTips(res){
        // 人脸打卡模式下需要授权薪工卡
        if(res.signInMode === 1){
            this.openSalary()
        }
        // 判断是否需要提现
        for (const i in res.salaryCollectionRecord) {
            if (res.salaryCollectionRecord[i].status === 0 || res.salaryCollectionRecord[i].status === 3 || res.salaryCollectionRecord[i].status === 4) {
                toBeWithdrawn = true
                this.setData({
                    toBeWithdrawn
                })
                break
            }
        }
        
    },
    // 点击拍照打卡逻辑
    onPhoto(){},
    // 点击beacon逻辑
    onBeacon(){},
    // 点击人脸识别逻辑
    onFace(){},

    // 开通微工卡提示
    openSalary(){
        querySalaryCard(this.data.companyId).then(() => {}, err => {
            app.alert('您还未开启微工卡授权，授权后才可打卡核身').then(() => {
                openSalaryCard(err ? this.data.companyId : '')
            })
        })
    },


    // 停止获取位置
    stopLocation() {
        wx.stopLocationUpdate()
        wx.offLocationChange()
    },

    // 搜索beacon
    scanfIBeacon() {
        // 弹出搜索界面
        this.setData({
            isScanf: true
        })
        // 开始搜索beacon
        scanfIBeacon(this.data.macAddressList).then(res => {
            console.log('回调', res)
            // 检查beacon是否在项目设备列表中
            ibeaconCheck({
                projectId: this.data.optionsId,
                macAddressList: res
            }).then(() => {
                this.setData({
                    devices: res,
                    isScanf: false
                })
                // 找到beacon走人脸识别流程
                this.verifyPreOrder()
            }, () => {
                this.setData({
                    isScanf: false
                })
                reportEvent('clock', {
                    status: 0,
                    failmsg: 'device',
                    userid: user.userId,
                    remark: '通过接口核验附近无设备'
                })
            })

        }, err => {
            if (err) {
                this.setData({
                    isScanf: false
                })
                app.alert(err)
                reportEvent('clock', {
                    'status': 0,
                    'failmsg': 'device',
                    'userid': user.userId,
                    'remark': err
                })
            }
        })
    },
    stopScanf() {
        stopScanfIBeacon()
    },
    // 打卡接口
    clockOut() {
        if(this.data.circularColour  && this.data.signInMode == 0){
            this.photoClock()
        }
        else if (this.data.circularColour || this.data.optionsType === '0') {
            if (this.data.signInType) {
                this.scanfIBeacon()
            } else {
                this.verifyPreOrder()
            }
        } else {
            wx.getSetting({
                success: (res) => {
                    if (!res.authSetting['scope.userLocation'] && circularColour) {
                        app.alert('未授权获取位置信息权限无法打卡，请授权后再试').then(()=>{
                            wx.openSetting()
                        })
                        
                    }
                    else{
                        app.alert('当前不在打卡时间或不在打卡区域内，请确认您的位置或联系管理员，查看手机定位是否打开')
                    }
                }
            })
        }
    },
    updateTime: function () {
        let myDate = new Date()
        let currentTime = dateFormat('HH:MM:SS', myDate)
        this.setData({
            currentTime: currentTime,
        })
    },
    updateDate: function (event) {
        this.stopLocation()
        this.initShow(event.detail)
    },
    goToPath() {
        wx.navigateTo({
            url: '/pages/salary/salary'
        })
    },
    // 人脸识别
    verifyPreOrder() {
        console.log(this.data.detailList)
        verifyFace({
            openid: user.openid,
            companyId: this.data.companyId,
            projectId: this.data.optionsId,
            employerName: this.data.detailList.serveCompanyName,
            projectName: this.data.detailList.serveCompanyName,
            userName: user.userName,
            idCardNumber: user.cardNo,
            employmentType: 'SHORT_TERM_EMPLOYMENT',
            authenticateType: 'SIGN_IN'
        }).then(res => {
            this.static.authenticateNumber = res.authenticateNumber
        })
    },
    // 最终打卡入库
    punchIn(){
        let myDate = new Date()
        postPunchIn({
            projectId: this.data.optionsId,
            signLocation: this.data.longitude + ',' + this.data.latitude,
            signTime: dateFormat('HH:MM:SS', myDate),
            date: dateFormat('YY-mm-dd', myDate),
            macAddressList: this.data.devices,
            signVoucher: this.static.signVoucher
            // isNormal:this.data.isNormal
        }).then(() => {
            reportEvent('clock', {
                'status': 1,
                'failmsg': 'none',
                'userid': user.userId,
                'remark': '打卡成功'
            })
            this.initShow(this.data.changeDate)
            if(!this.static.signVoucher){
                toast('打卡成功', 2000)
            }
        },err=>{
            reportEvent('clock', {
                'status': 0,
                'failmsg': 'service',
                'userid': user.userId,
                'remark': err
            })
        })
    },
    // 拍照打卡
    photoClock(){
        wx.chooseMedia({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['camera']
        }).then(res=>{
            console.log(this.data.formatAddress)
            wx.uploadFile({
                url: global.baseUrl + '/api/v1/blue/blue-sign/upload',
                filePath: tempFiles[0].tempFilePath,
                name: 'file',
                formData: {
                    'signAddress': this.data.formatAddress
                },
                success: res => {
                    this.static.signVoucher = JSON.parse(res.data).data.fileUrl
                    this.punchIn()
                    wx.navigateTo({
                        url: '/pages/success/success?title=' + '上传成功' + '&content=' + '已完成打卡' + '&signVoucher=' + JSON.parse(res.data).data.fileUrl ,
                    })
                },
                fail(){
                    app.toast('图片上传失败！')
                }
            })
        })

    }


})